package com.book.business.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.book.business.entity.BookCart;
import com.book.business.entity.BookLove;
import com.book.business.entity.BookSell;
import com.book.business.service.BookCartService;
import com.book.business.service.BookLoveService;
import com.book.business.service.BookSellService;
import com.book.common.annotation.ControllerEndpoint;
import com.book.common.annotation.Log;
import com.book.common.controller.BaseController;
import com.book.common.entity.FebsConstant;
import com.book.common.entity.FebsResponse;
import com.book.common.entity.QueryRequest;
import com.book.common.utils.FebsUtil;
import com.book.common.utils.BookMethod;
import com.book.shelves.entity.BookStore;
import com.book.shelves.entity.ShelvesApply;
import com.book.shelves.service.BookStoreService;
import com.book.shelves.service.ShelvesApplyService;
import com.book.warehouse.entity.WarehouseBook;
import com.book.warehouse.service.WarehouseBookService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.Map;

/**
 * @Author: 盛佳帅
 * @Description: 20173953
 */

@Controller
public class BookSellController extends BaseController {
    @Autowired
    BookSellService bookSellService;
    @Autowired
    BookLoveService bookLoveService;
    @Autowired
    BookCartService bookCartService;
    @Autowired
    WarehouseBookService warehouseBookService;
    @Autowired
    BookStoreService bookStoreService;
    @Autowired
    ShelvesApplyService shelvesApplyService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "business/bookSell")
    public String bookSellIndex() {
        return FebsUtil.view("business/sell/bookSellList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "business/bookSell/add")
    public String bookSellAdd() {
        return FebsUtil.view("business/sell/bookSellAdd");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "business/bookSell/update/{id}")
    public String bookSellUpdate(@PathVariable Integer id, ModelMap modelMap) {
        BookSell bookSell = this.bookSellService.getById(id);
        modelMap.put("bookSell", bookSell);
        return FebsUtil.view("business/sell/bookSellUpdate");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "business/bookSell/cart/{id}")
    public String bookSellCart(@PathVariable Integer id, ModelMap modelMap) {
        BookSell bookSell = this.bookSellService.getById(id);
        modelMap.put("bookSell", bookSell);
        return FebsUtil.view("business/sell/bookSellToCart");
    }

    @GetMapping("bookSell")
    @ResponseBody
    @RequiresPermissions("bookSell:view")
    public FebsResponse bookSellList(BookSell bookSell) {
        return new FebsResponse().success().data(this.bookSellService.findBookSell(bookSell));
    }

    @Log("访问售书窗口")
    @GetMapping("bookSell/list")
    @ResponseBody
    @RequiresPermissions("bookSell:view")
    public FebsResponse bookSellIPage(QueryRequest request, BookSell bookSell) {
        Map<String, Object> dataTable = getDataTable(this.bookSellService.pageBookSell(request, bookSell));
        return new FebsResponse().success().data(dataTable);
    }

    @Log("售书-申请上架")
    @PostMapping("bookSell/{bookname}")
    @ResponseBody
    @RequiresPermissions("bookSell:add")
    @ControllerEndpoint(operation = "新增上架书籍", exceptionMessage = "上架新增失败")
    public FebsResponse bookSellAdd(@PathVariable String bookname) {
        List<WarehouseBook> warehouseBookList = warehouseBookService.list(new QueryWrapper<WarehouseBook>().lambda().in(WarehouseBook::getBookname, Arrays.asList(bookname.split(","))));
        for (int i = 0; i < warehouseBookList.size(); i++) {
            ShelvesApply shelvesApply = shelvesApplyService.getOne(new QueryWrapper<ShelvesApply>().lambda()
                    .eq(ShelvesApply::getBookid, warehouseBookList.get(i).getBookid()).eq(ShelvesApply::getStatus,"0"));
            if (shelvesApply != null) {
                return new FebsResponse().message("书籍正在申请上架，请耐心等候！");
            }
            if (warehouseBookList.get(i).getNumber() == 0) {
                return new FebsResponse().message("“"+warehouseBookList.get(i).getBookname()+"”，该书籍已售空！");
            }
            shelvesApplyService.save(new ShelvesApply().setBookid(warehouseBookList.get(i).getBookid()).setStatus("0"));
        }
        return new FebsResponse().success();
    }

    @Log("售书-申请下架")
    @PostMapping("bookSell/delete/{ids}")
    @ResponseBody
    @RequiresPermissions("bookSell:delete")
    @ControllerEndpoint(operation = "申请下架成功", exceptionMessage = "申请下架失败")
    public FebsResponse bookSelldelete(@PathVariable String ids) {
        List<BookSell> bookSellList = bookSellService.list(new QueryWrapper<BookSell>().lambda().in(BookSell::getId, Arrays.asList(ids.split(","))));
        for (int i = 0; i < bookSellList.size(); i++) {
            shelvesApplyService.save(new ShelvesApply().setBookid(bookSellList.get(i).getId()).setStatus("1"));
        }
        return new FebsResponse().success();
    }

    @Log("售书-加入购物车")
    @PostMapping("bookSell/cart")
    @ResponseBody
    @RequiresPermissions("bookSell:cart")
    @ControllerEndpoint(operation = "加入购物车成功", exceptionMessage = "加入购物车失败")
    public FebsResponse bookCart(@Valid BookSell bookSell) {
        QueryWrapper<BookCart> bookCartQueryWrapper = new QueryWrapper<>();
        bookCartQueryWrapper.eq("bookname", bookSell.getBookname())
                .eq("pubid", bookSell.getPubid());
        BookCart bookCart = bookCartService.getOne(bookCartQueryWrapper);
        QueryWrapper<BookSell> bookSellQueryWrapper = new QueryWrapper<>();
        bookSellQueryWrapper.eq("bookname", bookSell.getBookname())
                .eq("pubid", bookSell.getPubid());
        BookSell bookSell1 = bookSellService.getOne(bookSellQueryWrapper);
        if (bookSell.getNumber() == 0) {
            return new FebsResponse().message("不能添加0本，请规范填写");
        }
        if (bookSell1.getNumber() == 0) {
            return new FebsResponse().message("非常抱歉！该书籍已售空！");
        }
        if (bookSell1.getNumber() < bookSell.getNumber()) {
            return new FebsResponse().message("商家近期预售还剩" + bookSell1.getNumber() + "本" + bookSell.getBookname() + "，请重新添加购物车");
        }
        if (bookCart == null) {
            bookCart = new BookCart()
                    .setUsername(getCurrentUser().getUsername())
                    .setBookname(bookSell.getBookname())
                    .setType(bookSell.getType())
                    .setBookmoney(bookSell.getBookmoney())
                    .setMessage(bookSell.getMessage())
                    .setPubid(bookSell.getPubid())
                    .setNumber(bookSell.getNumber());
            bookCartService.addBookCart(bookCart);
            bookSell1.setCart(1);
            bookSellService.updateBookSell(bookSell1);
        } else {
            bookCart.setNumber(bookCart.getNumber() + bookSell.getNumber());
            bookCartService.updateBookCart(bookCart);
        }
        return new FebsResponse().success();
    }

    @Log("售书-加入收藏夹")
    @PostMapping("bookSell/love/{id}")
    @ResponseBody
    @RequiresPermissions("bookSell:love")
    @ControllerEndpoint(operation = "添加收藏成功", exceptionMessage = "添加收藏失败")
    public FebsResponse bookLove(@PathVariable Integer id, ModelMap modelMap) {
        BookSell bookSell = bookSellService.getById(id);
        QueryWrapper<BookLove> bookLoveQueryWrapper = new QueryWrapper<>();
        bookLoveQueryWrapper.eq("bookname", bookSell.getBookname());
        BookLove bookLove = bookLoveService.getOne(bookLoveQueryWrapper);
        if (bookLove == null) {
            bookLove = new BookLove()
                    .setUsername(getCurrentUser().getUsername())
                    .setBookname(bookSell.getBookname())
                    .setType(bookSell.getType())
                    .setPubid(bookSell.getPubid())
                    .setBookmoney(bookSell.getBookmoney())
                    .setMessage(bookSell.getMessage());
            bookLoveService.addBookLove(bookLove);
            bookSell.setLove(1);
            bookSellService.updateBookSell(bookSell);
            return new FebsResponse().success();
        } else {
            bookLoveService.removeById(bookLove.getId());
            bookSell.setLove(0);
            bookSellService.updateBookSell(bookSell);
            return new FebsResponse().message("取消收藏成功");
        }
    }
}

